package com.qyhl.school.school.reporter.clue;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.ninephotolayout.BGASortableNinePhotoLayout;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SCHOOL_REPORTER_CLUE)
public class SchoolReportClueActivity extends BaseActivity
        implements SchoolReportClueContact.SchoolReportClueView, BGASortableNinePhotoLayout.Delegate {
    @BindView(R2.id.title)
    EditText title;
    @BindView(R2.id.num_tip)
    TextView numTip;
    @BindView(R2.id.content)
    EditText content;
    @BindView(R2.id.NinePhotoLayout)
    BGASortableNinePhotoLayout NinePhotoLayout;
    @BindView(R2.id.location)
    TextView mLocation;
    @BindView(R2.id.phone)
    EditText phone;

    private SchoolReportCluePresenter mPresenter;
    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 200;

    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private String upContent;

    private String upPhone;

    private String upTitle;

    private String upAddress;

    private String username;

    private double upLng = 0;
    private double upLat = 0;

    private String[] locationChoose = {"是", "否"};
    private int mIndex = 0;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_reporter_clue;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SchoolReportCluePresenter(this);

        initLocation();

        //九宫格设置监听
        NinePhotoLayout.setDelegate(this);

        mPresenter.getToken(false);
    }

    private void initLocation() {
        //--------------------------------------定位--------------------------------------
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(15000);

        mLocationOption.setInterval(2000);

        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);

    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    upLng = aMapLocation.getLongitude();
                    upLat = aMapLocation.getLatitude();
                    upAddress = aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum() + aMapLocation.getAoiName() + aMapLocation.getBuildingId();
                    mLocation.setText(upAddress);
                } else {
                    showToast("定位失败！");
                    mLocation.setText("所在位置");
                    upLng = 0;
                    upLat = 0;
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
            mLocationClient.stopLocation();
        }
    };

    @Override
    protected void setListener() {
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                numTip.setText("内容（" + content.getText().toString().length() + "/500字）");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void checkData() {
        username = CommonUtils.getInstance().getUserName();

        upContent = content.getText().toString();
        if (StringUtils.isEmpty(upContent)) {
            showToast("请填写线索描述！");
            dismissLoading();
            return;
        }

        upTitle = title.getText().toString();
        if (StringUtils.isEmpty(upTitle)) {
            showToast("请填写线索标题！");
            dismissLoading();
            return;
        }

        upAddress = mLocation.getText().toString();
        if (StringUtils.isEmpty(upAddress) || upAddress.equals("所在位置")) {
            upAddress = "";
            upLat = 0;
            upLng = 0;
        }

        upPhone = phone.getText().toString();
        if (StringUtils.isEmpty(upPhone)) {
            upPhone = "";
        }

        if (selectedList != null && selectedList.size() > 0) {
            if (mUpToken == null) {
                mPresenter.getToken(true);
                return;
            }
            List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
            for (int i = 0; i < selectedList.size(); i++) {
                LocalMedia image = selectedList.get(i);
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(image.getCompressPath());
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
            }
            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getToken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    dismissLoading();
                    showToast("上传图片出错!");
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < files.size(); i++) {
                        if (i == files.size() - 1) {
                            stringBuilder.append(files.get(i).getUrl());
                        } else {
                            stringBuilder.append(files.get(i).getUrl()).append(",");
                        }
                    }

                    mPresenter.postClue(username, upTitle, upContent, upAddress, upPhone, upLng, upLat, stringBuilder.toString());

                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        } else {
            mPresenter.postClue(username, upTitle, upContent, upAddress, upPhone, upLng, upLat, "");
        }

    }

    @Override
    public void postResult(boolean isSuccess, String msg) {
        dismissLoading();
        showToast(msg);
        if (isSuccess) {
            finish();
        }
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            dismissLoading();
            showToast("提交失败！");
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        PictureSelector.create(SchoolReportClueActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_REQUEST);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        for (int i = 0; i < selectedList.size(); i++) {
            if (selectedList.get(i).getCompressPath().equals(NinePhotoLayout.getData().get(position))) {
                selectedList.remove(i);
            }
        }

        NinePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        MNImageBrowser.showImageBrowser(this, view, position, models);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        if (requestCode == CHOOSE_REQUEST) {
            resultList = PictureSelector.obtainMultipleResult(data);
            if (resultList != null && resultList.size() > 0) {
                selectedList.clear();
                selectedList.addAll(resultList);
            }
            ArrayList<String> select = new ArrayList<>();

            for (int i = 0; i < selectedList.size(); i++) {
                select.add(selectedList.get(i).getCompressPath());
            }

            NinePhotoLayout.setData(select);
        }
    }


    @OnClick({R2.id.back_btn, R2.id.location, R2.id.post_btn})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.location) {
            XXPermissions.with(SchoolReportClueActivity.this)
                    .permission(Permission.ACCESS_FINE_LOCATION)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(SchoolReportClueActivity.this);
                                builder.setTitle("是否显示当前所在地理位置？");
                                builder.setSingleChoiceItems(locationChoose, mIndex, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        mIndex = which;
                                    }
                                });
                                builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if ("是".equalsIgnoreCase(locationChoose[mIndex])) {
                                            mLocationClient.startLocation();
                                        } else {
                                            mLocation.setText("所在位置");
                                        }
                                        dialog.dismiss();
                                    }
                                }).show();
                            }
                        }
                    });
        } else if (id == R.id.post_btn) {
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        showLoading();
                        checkData();
                    } else {
                        showToast("尚未登录或登录已失效！");
                        RouterManager.routerLogin(SchoolReportClueActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        }
    }
}
